<?php
namespace App\HttpController\Api\VersionOne;

use App\Logic\CouponsLogic;
use App\Model\CouponsGroupLogModel;
use App\Model\CouponsGroupModel;
use App\Model\CouponsUserModel;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\AnnotationTag\Param;
use EasySwoole\HttpAnnotation\AnnotationTag\Method;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Pool\Exception\PoolEmpty;
use Throwable;

class Coupons extends VersionBase
{
    /**
     * index
     * 显示用户优惠券列表
     * @Method(allow={POST})
     * @Param(name="user_id", alias="用户ID", required="", integer="", min="1", notEmpty="不能为空")
     * @Param(name="status", alias="状态", required="", integer="", min="1", lengthMax="1", notEmpty="不能为空")
     * @Param(name="pn", alias="分页", required="", integer="", min="1", notEmpty="不能为空")
     */
    public function index()
    {
        $userId = $this->input('user_id', 0);
        $status = $this->input('status', 1);

        $requestParamData = [
            'userId' => $userId,
            'status' => $status,
        ];

        try {
            $res = CouponsLogic::userCouponsList($requestParamData);
        } catch (Exception $e) {
            $res = [];
        } catch (PoolEmpty $e) {
            $res = [];
        } catch (Throwable $e) {
            $res = [];
        }

        $this->writeJson(Status::CODE_OK, $res, "success");

        return true;
    }

    /**
     * newcomerPackage
     * 新人大礼包
     * @Method(allow={POST})
     * @Param(name="user_id", alias="用户ID", required="", integer="", min="1", notEmpty="不能为空")
     */
    public function newcomerPackage()
    {
        $userId = $this->input('user_id', 0);
        try {
            $group = $this->couponsGroupList($userId, 1);
        } catch (Exception $e) {
            $group = [];
        } catch (PoolEmpty $e) {
            $group = [];
        } catch (Throwable $e) {
            $group = [];
        }

        if (count($group) > 0) {
            try {
                $result = $this->addBatchUserCoupons($group);
            } catch (Exception $e) {
                $result = false;
            } catch (PoolEmpty $e) {
                $result = false;
            } catch (Throwable $e) {
                $result = false;
            }
            if ($result) {
                $this->writeJson(Status::CODE_OK, [], "领取成功");
            } else {
                $this->writeJson(Status::CODE_BAD_GATEWAY, [], "添加失败");
            }
        } else {
            $this->writeJson(Status::CODE_OK, [], "已领取新人大礼包");
        }

        return true;
    }

    /**
     * 查询优惠券组
     * @param int $userId
     * @param int $couponsGroupId
     * @return array
     * @throws Exception
     * @throws PoolEmpty
     * @throws Throwable
     */
    private function couponsGroupList(int $userId = 0, int $couponsGroupId = 0)
    {
        $isExist = DbManager::getInstance()->invoke(function ($client) use ($userId) {
            return CouponsGroupLogModel::invoke($client)->where('user_id', $userId)->all();
        });

        if (count($isExist) <= 0) {
            return [];
        }

        $total = 0;
        $data = [];
        $list = DbManager::getInstance()->invoke(function ($client) use ($couponsGroupId) {
            return CouponsGroupModel::invoke($client)->where('type_id', $couponsGroupId)->all();
        });

        if (count($list) <= 0) {
            return [];
        }

        foreach ($list as $group) {
            for ($i = 0; $i < $group->num; $i++) {
                array_push($data, ['user_id' => $userId, 'coupons_id' => $group->coupons_id, 'validate_time' => (time() + 7 * 86400), 'status' => 1,]);
                $total++;
            }
        }
        if ($total > 0) {
            // 添加领取记录
            DbManager::getInstance()->invoke(function ($client) use ($userId, $couponsGroupId) {
                $couponsGroupLogModel = CouponsGroupLogModel::invoke($client);
                $couponsGroupLogModel->group_id = $couponsGroupId;
                $couponsGroupLogModel->user_id = $userId;
                $couponsGroupLogModel->create_time = time();
                return $couponsGroupLogModel->save();
            });

            return $data;
        } else {
            return [];
        }
    }

    /**
     * 批量添加用户优惠券处理
     * @param array $data
     * @return bool
     * @throws Exception
     * @throws PoolEmpty
     * @throws Throwable
     */
    private function addBatchUserCoupons(array $data = [])
    {
        $total = count($data);
        if ($total > 0) {
            $insertData = DbManager::getInstance()->invoke(function ($client) use ($data) {
                return CouponsUserModel::invoke($client)->saveAll($data, false, true);
            });

            if (!$insertData) {
                return false;
            }

            if ($total == count($insertData)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}